package com.stone.serverless.web;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.startup.Tomcat;
import org.apache.tomcat.util.modeler.Registry;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import java.io.File;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/18 8:53
 * @Version: 1.0.0
 */
public class TomcatServer {

    public ServletContext servletContext;

    private Tomcat tomcat;

    public void run(WebApplicationContext webApplicationContext) {
        Registry.disableRegistry();
        String workspace = System.getProperty("user.dir");
        tomcat = new Tomcat();
        tomcat.setPort(8888);//设置端口
        // 看源码发现,他只能设置一个service,直接拿默认的
        Service service = tomcat.getService();
        service.setParentClassLoader(this.getClass().getClassLoader());
        // 创建连接器,并且添加对应的连接器,同时连接器指定端口
        Connector connector = new Connector();
        connector.setPort(8888);
        service.addConnector(connector);
        // 在对应的host下面创建一个 context 并制定他的工作路径,会加载该目录下的所有class文件,或者静态文件
        StandardContext context = (StandardContext) tomcat.addContext("/", null);
        context.setParentClassLoader(this.getClass().getClassLoader());
        Tomcat.addServlet(context, "myServlet", new DispatcherServlet(webApplicationContext)); //配置servlet
        servletContext = context.getServletContext();

        context.addServletMappingDecoded("/", "myServlet");//配置servlet映射路径
        StandardServer server = (StandardServer) tomcat.getServer();//添加监听器，不知何用
        AprLifecycleListener listener = new AprLifecycleListener();
        server.addLifecycleListener(listener);
        //设置appBase为项目所在目录
        tomcat.getHost().setAppBase(
                workspace + File.separator + "."

        );
        Thread thread = new Thread(() -> {
            //tomcat启动
            try {
                tomcat.start();
            } catch (LifecycleException e) {
                e.printStackTrace();
            }
            //保持主线程不退出
            tomcat.getServer().await();
        });
        thread.setContextClassLoader(this.getClass().getClassLoader());
        thread.start();

    }

    public void stop() {
        try {
            this.tomcat.stop();
        } catch (LifecycleException e) {
            e.printStackTrace();
            this.stop();
        }
    }
}
